function Snake(el) {

    // 保存地图对象
    this.el = el

    // 蛇节长度
    this.len = 20

    // 存蛇
    this.snakeObj = [
      { x: 3, y :2, color:"black", el:null},  //蛇头
      { x: 2, y :2, color:"white", el:null}, // 蛇的身体
      { x: 1, y :2, color:"white", el:null}  // 蛇的身体
    ]

    // 方向
    this.direction = "right"
}

Snake.prototype.remove = function() {

    
    // 循环遍历创建蛇
    for (let i = 0; i<this.snakeObj.length; i++) 
    {
        // 单独保存蛇节对象
       
        if (this.snakeObj[i].el)
        {
            this.el.removeChild(this.snakeObj[i].el)
        }
    }
}

Snake.prototype.create = function() 
{
    // 从地图上清除蛇
    this.remove()

    // 循环遍历创建蛇
    for (let i = 0; i<this.snakeObj.length; i++) 
    {

        // 1. 创建蛇标签对象
        let divObj = document.createElement("div")
        // 2. 设置宽度高度 坐标 颜色
        divObj.style.width = this.len + "px"
        divObj.style.height = this.len + "px"
        divObj.style.position = "absolute"
        divObj.style.borderRadius="50% 50%"
        divObj.style.left =  this.snakeObj[i].x*this.len+"px"
        divObj.style.top =  this.snakeObj[i].y *this.len+"px"
        divObj.style.background = this.snakeObj[i].color

        // 单独保存蛇节对象
        this.snakeObj[i].el = divObj
        // 3. 放到页面展示
        this.el.appendChild(divObj)
    }
}


Snake.prototype.move = function() {

    // 蛇头 上    y - 1
    // 蛇头 下    y + 1
    // 蛇头 左    x - 1
    // 蛇头 右    x + 1
    // 将构造函数中蛇的x数据+1
    // i > 0 不含蛇头 
    // i >= 0 含蛇头
    
    for (let i = this.snakeObj.length - 1; i>0; i--) {

        this.snakeObj[i].x = this.snakeObj[i-1].x
        this.snakeObj[i].y = this.snakeObj[i-1].y
    }

    switch (this.direction) {
        case "top":
            this.snakeObj[0].y -= 1
            break;
        case "bottom":
            this.snakeObj[0].y += 1
            break;
        case "left":
            this.snakeObj[0].x -= 1
            break;
        case "right":
            this.snakeObj[0].x += 1
            break;
    }
    
    // 重新创建
    this.create()
}